<template>
  <!-- 1、创建地图容器 -->
  <div id="my-map" class="my-map" style="height: 600px;width: 1000px;">
  </div>
</template>


<script>
import { Map, View } from 'ol'
import XYZ from 'ol/source/XYZ'
import {fromLonLat} from 'ol/proj'
import { Group, Tile } from 'ol/layer'

export default {
  data () {
    return {
      tk: '9aa421bfac4b31f0ad91a7118973689d',
      tdUrl: 'http://t4.tianditu.com/DataServer?T={lyr}&x={x}&y={y}&l={z}&tk=',
      // 卫星影像及注记
      lyr: ['img_w', 'cia_w'],
    }
  },
  methods: {
    initMap () {
      var img_layer = new Tile({
        crossOrigin: 'anonymous',
        source: new XYZ({
          url: 'http://t4.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=9aa421bfac4b31f0ad91a7118973689d'
        })
      });
      var cia_layer = new Tile({
        crossOrigin: 'anonymous',
        source: new XYZ({
          url: 'http://t4.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=9aa421bfac4b31f0ad91a7118973689d'
        })
      });
      var map = new Map({
        // 让id为map的div作为地图的容器
        target: 'my-map',
        // 设置地图图层
        layers: [
          this.getTileLayer(this.lyr),
          // img_layer, cia_layer
        ],
        // 设置显示地图的视图
        view: new View({
          center: fromLonLat([116.38094, 39.92361]),
          zoom: 12,
          maxZoom: 18,
          minZoom: 1,
        })
      });
    },
    // 获取瓦片数据
    getTileSource (lyr, url) {
      let newUrl = url.replace('{lyr}', lyr);
      return new XYZ({
        crossOrigin: 'anonymous',
        url: newUrl
      });
    },
    // 获取分组瓦片层
    getTileLayer (lyr) {
      return new Group({
        layers: lyr.map(item => {
          var tile = new Tile({
            crossOrigin: 'anonymous',
            source: this.getTileSource(item, this.tdUrl + this.tk)
          });
          return tile;
        })
      });
    },
  },
  mounted () {
    this.initMap();
  }
}
</script>

<style>

</style>